package com.qf.service.impl;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import com.auth0.jwt.JWT;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qf.entity.TlCar;
import com.qf.entity.TlPerson;
import com.qf.entity.TlTicket;
import com.qf.entity.TlUser;
import com.qf.mapper.CarMapper;
import com.qf.mapper.PersonMapper;
import com.qf.mapper.TicketMapper;
import com.qf.mapper.UserMapper;
import com.qf.service.TicketService;
import com.qf.utils.AliPayTools2;
import com.qf.utils.Mycode;
import com.qf.utils.RedisKey;
import com.qf.utils.ResultMsg;
import com.qf.vo.AdminTicketVo;
import com.qf.vo.TicketVo;
import com.qf.vo.TicketsVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class TicketServiceImpl extends ServiceImpl<TicketMapper, TlTicket> implements TicketService {

    @Autowired(required = false)
    CarMapper carMapper;

    @Autowired(required = false)
    PersonMapper personMapper;

    @Autowired(required = false)
    UserMapper userMapper;
    @Autowired
    RedisTemplate redisTemplate;


    /**
     * 查询当前用户的所有订单
     * @return 订单集合
     */
    @Override
    public ResultMsg findAll(HttpServletRequest request) {
        String uuid = request.getHeader("token");
        Object o = redisTemplate.boundValueOps(RedisKey.LOGIN_USER+uuid).get();
        if (o == null)
            return ResultMsg.ERROR(Mycode.NOTLOGIN_ERRO,"用户未登录");
        String token = (String) o;
        List<String> audience = JWT.decode(token).getAudience();
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("user_name", audience.get(0));
        TlUser tlUser = userMapper.selectOne(queryWrapper);//获得登录用户
        QueryWrapper<TlTicket> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id",tlUser.getUserId());
        List<TlTicket> list = super.list(wrapper);//查询当前用户订单
        ArrayList<AdminTicketVo> adminTicketVos = new ArrayList<>();//封装给前端的返回值
        if (list!=null) {
            for (TlTicket tlTicket : list) {
                TlPerson tlPerson = personMapper.selectById(tlTicket.getPersonId());
                adminTicketVos.add(new AdminTicketVo(tlUser.getUserName(),tlPerson.getPersonFlag(),tlPerson.getPersonName(),tlTicket));
            }
            return ResultMsg.SUCCESS(adminTicketVos);
        }
        return ResultMsg.ERROR(Mycode.TICKETFIND_ERRO,"查询订单有误");//订单为空
    }

    /**
     * 后台分页查询所有订单
     * @param page
     * @param limit
     * @return
     */
    @Override
    public ResultMsg findAll(int page, int limit) {
        Page<TlTicket> tlTicketPage = new Page<>(page, limit);
        Page<TlTicket> page1 = super.page(tlTicketPage);
//        ArrayList<AdminTicketVo> adminTicketVos = new ArrayList<>();
        ArrayList<AdminTicketVo> adminTicketVos = new ArrayList<>();
        Page<AdminTicketVo> adminTicketVoPage = new Page<>();
        if (page1!=null){
            List<TlTicket> records = page1.getRecords();
            for (TlTicket tlTicket : records) {
                TlUser tlUser = userMapper.selectById(tlTicket.getUserId());
                TlPerson tlPerson = personMapper.selectById(tlTicket.getPersonId());
                adminTicketVos.add(new AdminTicketVo(tlUser.getUserName(),tlPerson.getPersonFlag(), tlPerson.getPersonName(), tlTicket));
            }

            adminTicketVoPage.setRecords(adminTicketVos);
            adminTicketVoPage.setSize(page1.getSize());
            adminTicketVoPage.setTotal(page1.getTotal());
        }
        return ResultMsg.SUCCESS(adminTicketVoPage);
    }

    /**
     * 后台查询所有用户的所有订单
     * @return 订单集合
     */
    @Override
    public ResultMsg findAll() {
        List<TlTicket> list = super.list();
        ArrayList<AdminTicketVo> adminTicketVos = new ArrayList<>();
        if (list!=null) {
            for (TlTicket tlTicket : list) {
                TlUser tlUser = userMapper.selectById(tlTicket.getUserId());
                TlPerson tlPerson = personMapper.selectById(tlTicket.getPersonId());
                adminTicketVos.add(new AdminTicketVo(tlUser.getUserName(),tlPerson.getPersonFlag(), tlPerson.getPersonName(), tlTicket));
            }
            return ResultMsg.SUCCESS(adminTicketVos);
        }
        return ResultMsg.ERROR(Mycode.TICKETFIND_ERRO,"查询有误");//订单为空
    }

    /**
     * 提交订单
     * @param map 包含personId,carId,ticketLev
     * @return
     */
    @Override
    public ResultMsg submit(Map<String,Integer> map) {
        if (map!=null) {
            int personId = (int) map.get("personId");
            TlPerson tlPerson = personMapper.selectById(personId);
            int carId = (int) map.get("carId");
            TlCar tlCar = carMapper.selectById(carId);
            int ticketLev = (int) map.get("ticketLev");
            Snowflake snowflake = IdUtil.createSnowflake(0, 0);
            String ticketId = snowflake.nextIdStr();
            TlTicket tlTicket = new TlTicket(ticketId, tlPerson.getUserId(), tlPerson.getPersonId(), tlCar.getCarName(), tlCar.getCarStartaddr(), tlCar.getCarStarttime(), tlCar.getCarEndaddr(), tlCar.getCarEndtime(), 0, tlCar.getCarPrice(), ticketLev, tlPerson);
            boolean b = super.saveOrUpdate(tlTicket);
            if (b) {
                if (ticketLev == 0)//一等
                    tlCar.setCarFirst(tlCar.getCarFirst() - 1);
                if (ticketLev == 1)//二等
                    tlCar.setCarSec(tlCar.getCarSec() - 1);
                if (ticketLev == 2)//无座
                    tlCar.setCarNo(tlCar.getCarNo() - 1);
                int i = carMapper.updateById(tlCar);
                if (i == 1) {
                    TicketVo ticketVo = new TicketVo(tlPerson, tlCar);
                    return ResultMsg.SUCCESS(ticketVo);
                }
            }
        }
        return ResultMsg.ERROR(Mycode.TICKETSUBMIT_ERRO,"订单提交失败");//订单提交失败
    }

    /**
     *  删除订单
     * @param ticketId 订单编号
     * @return
     */
    @Override
    public ResultMsg delete(String ticketId) {
        TlTicket byId = super.getById(ticketId);
        int ticketLev = byId.getTicketLev();
        String carName=byId.getTicketCarname();
        QueryWrapper<TlCar> wrapper = new QueryWrapper<>();
        wrapper.eq("car_name",carName);
        TlCar tlCar = carMapper.selectOne(wrapper);
        boolean b = super.removeById(ticketId);
        if (b){
            if (ticketLev == 0)//一等
                tlCar.setCarFirst(tlCar.getCarFirst() + 1);
            if (ticketLev == 1)//二等
                tlCar.setCarSec(tlCar.getCarSec() + 1);
            if (ticketLev == 2)//无座
                tlCar.setCarNo(tlCar.getCarNo() + 1);
            int i = carMapper.updateById(tlCar);
            if (i == 1) {
                return ResultMsg.SUCCESS();
            }
        }
        return ResultMsg.ERROR(Mycode.TICKETDELETE_ERRO,"删除失败");
    }

    @Override
    public ResultMsg create(TicketsVo ticketsVo,HttpServletRequest request) {
        //获取用户信息
        String uuid = request.getHeader("token");
        Object o = redisTemplate.boundValueOps(RedisKey.LOGIN_USER+uuid).get();
        if (o == null)
            return ResultMsg.ERROR(Mycode.NOTLOGIN_ERRO,"用户未登录");
        String token = (String) o;
        List<String> audience = JWT.decode(token).getAudience();
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("user_name", audience.get(0));
        //获得登录用户
        TlUser tlUser = userMapper.selectOne(queryWrapper);
        List<TlPerson> personList = ticketsVo.getPersonList();
        String carName = ticketsVo.getCarName();
        //获得车次信息
        QueryWrapper<TlCar> Wrapper = new QueryWrapper<>();
        Wrapper.eq("car_name",carName);
        TlCar tlCar = carMapper.selectOne(Wrapper);
        for (TlPerson tlPerson : personList) {
            String seatInfo = tlPerson.getSeatInfo();
            //座位信息
            Integer sit = Integer.valueOf(seatInfo);
            //乘车人id
            QueryWrapper<TlPerson> wrapper = new QueryWrapper<>();
            wrapper.eq("person_card",tlPerson.getPersonCard());
            TlPerson tlPerson1 = personMapper.selectOne(wrapper);
            Snowflake snowflake = IdUtil.createSnowflake(0, 0);
            String ticketId = snowflake.nextIdStr();
            TlTicket tlTicket = new TlTicket(ticketId,tlUser.getUserId(),tlPerson1.getPersonId(),tlCar.getCarName(),tlCar.getCarStartaddr(),tlCar.getCarStarttime(),tlCar.getCarEndaddr(),tlCar.getCarEndtime(),0,tlCar.getCarPrice(),sit,null);
            boolean b = super.saveOrUpdate(tlTicket);
            if (b){
                if (sit==0){
                    tlCar.setCarFirst(tlCar.getCarFirst()-1);
                }
                if (sit==1){
                    tlCar.setCarSec(tlCar.getCarSec()-1);
                }
                if (sit==2){
                    tlCar.setCarNo(tlCar.getCarNo()-1);
                }
                carMapper.updateById(tlCar);
            }
        }
        return ResultMsg.SUCCESS();
    }

    @Override
    public ResultMsg refund(String ticketId, Integer ticketPrice) {
        String s = AliPayTools2.tuiKuan(ticketId, ticketPrice);
        if (s.equals("Y")){
            boolean b = super.removeById(ticketId);
            if (b)
                return ResultMsg.SUCCESS();
            else
                return ResultMsg.ERROR(777);
        }else{
            return ResultMsg.ERROR(Mycode.TUIKUANSHIBAI,"退款失败");
        }
    }
}
